import {createStore} from 'vuex'
import Cookie from 'js-cookie'

const store = createStore({
    state:{
        isCollapse:true,
        currentMenu:null,
        tabsList:[
            {
                path:'/',
                name:'home',
                label:'首页',
                icon:'s-home',
            },
        ],
        menu:[],
        token:''
    },
    mutations:{
        UPDATE_COLLAPSE(state,payload){
            state.isCollapse = !state.isCollapse
        },
        SELECT_MENU(state,val){
            //判断
            // val.name == 'home' ? (state.currentMenu = null) : (state.currentMenu = val)
            if(val.name == 'home'){
                state.currentMenu = null
            }else{
                state.currentMenu = val
                let result = state.tabsList.findIndex(item => item.name === val.name)
                result == -1 ? state.tabsList.push(val) : ''
            }
        },
        CLOSE_TAG(state,val){
            let res = state.tabsList.findIndex(item => item.name === val.name) 
            state.tabsList.splice(res,1)
        },

        SET_MENU(state,val){
            state.menu = val
            localStorage.setItem('menu',JSON.stringify(val))
        },
        ADD_MENU(state,router){
            if(!localStorage.getItem('menu')) return
            const menu = JSON.parse(localStorage.getItem('menu'))
            state.menu = menu

            let routeArr = []
            menu.forEach(item => {
                if(item.children){
                    item.children = item.children.map(element => {
                        let url = `../views/${element.url}`
                        element.component = ()=>import(url)
                        return element
                    })
                    routeArr.push(...item.children)
                }else{
                    let url = `../views/${item.url}`
                    item.component = ()=>import(url)
                    routeArr.push(item)
                }
            });
            routeArr.forEach(item => {
                router.addRoute('home0',item)
            })
        },
        
        LOGIN_OUT(state){
            state.menu = []
            localStorage.removeItem('menu')
        },
        
        SET_TOKEN(state,val){
            state.token = val
            Cookie.set('token',val)
        },
        GET_TOKEN(state){
            state.token = state.token || Cookie.get('token')
        },
        CLEAR_TOKEN(state){
            state.token = ''
            Cookie.remove('token')
        },
    }
})
export default store